package com.yb0os1.strategy.controller;

import com.yb0os1.strategy.anno.SupportMemberType;
import com.yb0os1.strategy.enums.MemberType;
import com.yb0os1.strategy.serve.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@RestController
public class MemberController {


    @Autowired
    private MemberService defaultMember;
    Map<MemberType, MemberService> memberServiceMap;
    @Autowired
    public void setMemberServiceMap(List<MemberService> memberServices) {
        memberServiceMap = memberServices.stream()
                .filter(memberService -> memberService.getClass().isAnnotationPresent(SupportMemberType.class))
                .collect(Collectors
                        .toMap(this::findMemberTypeFromService,
                                Function.identity()));
        //Function.identity()就是函数本身，就是返回自己 等同于t->t
        if (memberServiceMap.size()!=MemberType.values().length){
            throw new RuntimeException("没有找到对应的会员类型");
        }
    }

    private MemberType findMemberTypeFromService(MemberService memberService){
        return memberService.getClass().getAnnotation(SupportMemberType.class).value();
    }
    @GetMapping("/member/{recharge}")
    public String getMember(@PathVariable("recharge") int recharge) {
        MemberType memberType = MemberType.getMemberType(recharge);
        MemberService memberService = memberServiceMap.getOrDefault(memberType, defaultMember);
        return memberService.findCustomer(recharge);
    }



}
